//
//  ST_KnighthoodLevelController.swift
//  btvideo
//
//  Created by Jason on 2021/8/30.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources
import SwiftyJSON

class ST_KnighthoodLevelController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = #colorLiteral(red: 0.1019607843, green: 0.1137254902, blue: 0.1529411765, alpha: 1)
        
        view.addSubview(own_navigation_bar)
        own_navigation_bar.snp.makeConstraints { (make) in
            make.right.left.top.equalTo(view)
            make.height.equalTo(statusBarHeight+44)
        }
        own_navigation_bar.addSubview(left_nav_btn)
        own_navigation_bar.addSubview(title_nav_btn)
        
        
        left_nav_btn.snp.makeConstraints { (make) in
            make.left.equalTo(own_navigation_bar).offset(8)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        title_nav_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(left_nav_btn)
            make.centerX.equalTo(own_navigation_bar)
        }
        
        title_nav_btn.setTitle("贵族特权", for: .normal)
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(160)
            make.top.equalToSuperview().offset(44+statusBarHeight+65)
        }
        
        view.addSubview(aristocratic_privilege_title_label)
        aristocratic_privilege_title_label.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(collectionView.snp.bottom).offset(30)
            make.height.equalTo(20)
        }
        
        view.addSubview(aristocratic_privilege_left_image_view)
        aristocratic_privilege_left_image_view.snp.makeConstraints { make in
            make.centerY.equalTo(aristocratic_privilege_title_label).offset(5)
            make.right.equalTo(aristocratic_privilege_title_label.snp.left).offset(-5)
            make.height.width.equalTo(16)
        }
        
        view.addSubview(aristocratic_privilege_right_image_view)
        aristocratic_privilege_right_image_view.snp.makeConstraints { make in
            make.centerY.equalTo(aristocratic_privilege_title_label).offset(5)
            make.left.equalTo(aristocratic_privilege_title_label.snp.right).offset(5)
            make.height.width.equalTo(16)
        }
        
        
        var lastVerticalView:ST_KnighthoodLevelCellChildBox?
        
        for idx in 0...3{
            
            let rowIndex = idx % 2
            
            let itemView = ST_KnighthoodLevelCellChildBox()
            itemView.alpha = 0
            view.addSubview(itemView)
            
            widgetViews.append(itemView)
            
            if rowIndex == 0{
                itemView.snp.makeConstraints { (make) in
                    make.size.equalTo(ST_AICenterFaceStatusCellChildBox.size)
                    make.left.equalToSuperview().offset(38)
                    
                    if let last = lastVerticalView{
                        make.top.equalTo(last.snp.bottom).offset(15)
                    }else{
                        make.top.equalTo(aristocratic_privilege_title_label.snp.bottom).offset(44)
                    }
                }
            }else{
                
                itemView.snp.makeConstraints { (make) in
                    make.size.equalTo(ST_AICenterFaceStatusCellChildBox.size)
                    make.right.equalToSuperview().offset(-38)
                    if let last = lastVerticalView{
                        make.top.equalTo(last)
                    }else{
                        make.top.equalTo(aristocratic_privilege_title_label.snp.bottom).offset(44)
                    }
                }
            }
            if rowIndex == 0{
                lastVerticalView = itemView
            }
        }
        
        
        
        bind_data()
    }
    
//    override func viewDidAppear(_ animated: Bool) {
//
//        super.viewDidAppear(animated)
//
//        let layoutMargins  =  collectionView.layoutMargins.left + collectionView.layoutMargins.right
//
//        let sideInset = (self.view.width / 2.0 ) - layoutMargins
//
//        collectionView.contentInset = UIEdgeInsets(top: 0, left: sideInset, bottom: 0, right: sideInset)
//
//    }
    
    
    
    fileprivate func bind_data(){
        
        TIANSession(requestUrl: PH.nobilityListApi).withUnretained(self).subscribe(onNext:{ own,result in
            
            
            switch result {
            case .success(let json):
                
                var list = json["data"].arrayValue.map({ ST_KnighthoodLevelModel(fromJson: $0) })
                
                let gap = ST_KnighthoodLevelModel(fromJson: JSON.null)
                
                gap.gapCell = true
                
                list.insert(gap, at: 0)
                
                list.append(gap)
                
                
                let items = Observable.just([
                            SectionModel(model: "", items: list)
                            ])
                         
                //创建数据源
                let dataSource = RxCollectionViewSectionedReloadDataSource
                    <SectionModel<String, ST_KnighthoodLevelModel>>(
                    configureCell: { (dataSource, collectionView, indexPath, element) in
                        
                        let cell = collectionView.dequeueReusableCell(withClass: ST_KnighthoodLevelCell.self, for: indexPath)
                        
                        cell.model = element
                        
                        return cell
                        
                    })
                         
                        //绑定单元格数据
                items
                    .bind(to: own.collectionView.rx.items(dataSource: dataSource))
                    .disposed(by: own.disposeBag)
                
                guard let myIdx = list.firstIndex(where: { $0.checked })?.uInt else{
                    return
                }
                
                own.collectionView.performBatchUpdates(nil, completion: {
                    (result) in
                    
                    let firstIndexPath = IndexPath(row: Int(myIdx), section: 0)
                    
                    if #available(iOS 13, *) {
                        own.collectionView.scrollToItem(at: firstIndexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: false)
                    } else {
                        own.collectionView.scrollToItem(at: firstIndexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
                    }
                    
                    
                    if let firstCell = (own.collectionView.cellForItem(at: firstIndexPath) as? ST_KnighthoodLevelCell){
                        
                        firstCell.transformToLarge()
                        
                        own.centerCell = firstCell
                    }
                    
                })
                
            case .failure(let err):
                own.toast(text: err.e)
            }
            
        }).disposed(by: disposeBag)
        
    }
    
    var disposeBag = DisposeBag()
    
    fileprivate lazy var layout:ST_KnighthoodLevelLayout = {
        let controlLayout = ST_KnighthoodLevelLayout()
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        
        control.register(cellWithClass: ST_KnighthoodLevelCell.self)
        
        control.backgroundColor = .random
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.delegate = self
        control.backgroundColor = .clear
        control.alwaysBounceHorizontal = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        return control
    }()
    
    fileprivate lazy var own_navigation_bar:UIView = {
        let control = UIView()
        control.backgroundColor = .clear
        return control
    }()
    
    fileprivate lazy var left_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImage(ST_ImageUtils.imageName("返回_white"), for: UIControl.State.normal)
        
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
        
//        control.backgroundColor = Color.random
        
        control.addTarget(self, action: #selector(left_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    
    fileprivate lazy var title_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleColorForAllStates(.white)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium)
        
        
        return control
    }()
    
//
    fileprivate lazy var aristocratic_privilege_title_label:UILabel = {
       let control = UILabel()
        control.font = .systemFont(ofSize: 14, weight: .regular)
        control.textColor = .white
        return control
    }()
    
    fileprivate lazy var aristocratic_privilege_left_image_view:UIImageView = {
        let v = UIImageView(image: ST_ImageUtils.imageName("贵族_number_left"))
        return v
    }()
    
    fileprivate lazy var aristocratic_privilege_right_image_view:UIImageView = {
        let v = UIImageView(image: ST_ImageUtils.imageName("贵族_number_right"))
        return v
    }()
    
    fileprivate var widgetViews = [ST_KnighthoodLevelCellChildBox]()
    
    
    fileprivate var centerCell:ST_KnighthoodLevelCell?{
        didSet{
            
//            desc
            guard let item_model = centerCell?.model else { return  }
            
            aristocratic_privilege_title_label.text = item_model.desc
            
            for (i,widgetView) in widgetViews.enumerated() {
                
                if let item = item_model.widget[safe: i]{
                    widgetView.model = item
                    widgetView.alpha = 1
                }else{
                    widgetView.alpha = 0
                }
                
            }
            
        }
    }
}

extension ST_KnighthoodLevelController:UICollectionViewDelegate{
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let centerPoint = CGPoint(x: scrollView.frame.size.width / 2 + scrollView.contentOffset.x, y: scrollView.frame.size.height / 2 + scrollView.contentOffset.y)
        
        
        if let indexPath = collectionView.indexPathForItem(at: centerPoint),self.centerCell == nil{
            
            self.centerCell = collectionView.cellForItem(at: indexPath) as? ST_KnighthoodLevelCell
            
            self.centerCell?.transformToLarge()
        }
        
        if let cell = self.centerCell{
            
            let offsetX = centerPoint.x - cell.center.x
            
            if offsetX < -35 || offsetX > 35 {
                cell.transformToStandard()
                self.centerCell = nil
            }
            
            
        }
        
    }
    
    
}


extension ST_KnighthoodLevelController{
    
    @objc fileprivate func left_click(){
        
        goback_previous_controller()
        
    }
}

